// routes/cws.js
const express = require("express");
const router = express.Router();
const { Useres,Messages} = require("../model/model");

// 登录/注册路由
router.post("/login", async (req, res) => {
  try {
    const { username, password, email } = req.body;

    // 邮箱格式验证
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!emailRegex.test(email)) {
      return res.status(400).json({ 
        error: {
          code: "INVALID_EMAIL",
          message: "无效的邮箱格式"
        }
      });
    }

    // 查找用户
    let user = await Useres.findOne({ username });

    // 自动注册
    if (!user) {
      if (!password || password.length < 6) {
        return res.status(400).json({
          error: {
            code: "WEAK_PASSWORD",
            message: "密码必须至少6个字符"
          }
        });
      }

      user = await Useres.create({
        username,
        password,
        email,
        online: true
      });
    } else {
      // 密码验证
      if (user.password !== password) {
        return res.status(401).json({
          error: {
            code: "INVALID_CREDENTIALS",
            message: "用户名或密码错误"
          }
        });
      }

      // 更新在线状态
      user = await Useres.findByIdAndUpdate(
        user._id,
        { online: true },
        { new: true }
      );
    }

    res.json({
      _id: user._id,
      username: user.username,
      email: user.email,
      online: user.online
    });

  } catch (error) {
    console.error("登录错误:", error);
    res.status(500).json({
      error: {
        code: "SERVER_ERROR",
        message: error.message
      }
    });
  }
});

router.get('/api/messages', async (req, res) => {
  try {
    const { userId, targetId } = req.query;
    const messages = await Message.find({
      $or: [
        { from: userId, to: targetId },
        { from: targetId, to: userId }
      ]
    }).sort({ timestamp: 1 });
    res.json(messages);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;